package com.lean.android.ad.network

import android.os.Build
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import com.lean.android.ad.core.AdSdk
import com.lean.android.ad.repository.localcache.AdLocalCache
import com.lean.android.ad.utils.AdLog
import com.lean.android.network.JsonFactory
import com.lean.android.sysinfo.OsDataProvider
import okhttp3.ConnectionPool
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import java.util.concurrent.TimeUnit

object NetworkFactory {

    private const val BASE_URL = "https://report-api.hnchjkj.cn"
    private const val TEST_BASE_URL = "http://192.168.2.227:8080"

    private fun createOkHttpClient(): OkHttpClient {
        val builder = OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS).writeTimeout(10, TimeUnit.SECONDS)
            .connectionPool(ConnectionPool(10, 5, TimeUnit.MINUTES))

        //interceptors.
        builder.addInterceptor { chain ->
            val request = chain.request().newBuilder().apply {
                addHeader("Package", AdSdk.appContext.packageName)
                addHeader("Channel", AdSdk.getAdConfig().channelInfoProvider.getChannel())
                addHeader("RealChannel", AdSdk.getAdConfig().channelInfoProvider.getRealChannel())
                addHeader("Version", AdSdk.getAdConfig().appInfoProvider.getVersion())
                addHeader("DeviceStartTime", AdLocalCache.deviceStartTime.toString())
                addHeader("Model", Build.MODEL)
                addHeader("AndroidVersion", Build.VERSION.SDK_INT.toString())
                addHeader("CurrentTime", (System.currentTimeMillis() / 1000).toString())
                if (AdLocalCache.oaid.isNotBlank()) {
                    addHeader("Oaid", AdLocalCache.oaid)
                }
                addHeader("DeviceId", AdLocalCache.deviceId)
                addHeader(
                    "IsAdbEnabled ", OsDataProvider.isAdbEnabled(AdSdk.appContext).toString()
                )
            }
            chain.proceed(request.build())
        }.addNetworkInterceptor(CacheNetworkInterceptor()).addInterceptor(
                HttpLoggingInterceptor { message ->
                    AdLog.d(AdLog.AdHttpTag, message)
                }.setLevel(HttpLoggingInterceptor.Level.BODY)
            )


        return builder.build()
    }

    private class CacheNetworkInterceptor : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {
            //无缓存，进行缓存
            val response = chain.proceed(chain.request())
            return response.newBuilder().removeHeader("Pragma")
                //对请求进行最大60秒的缓存
                .addHeader("Cache-Control", "max-age=60").build()
        }
    }

    fun createRetrofit(): Retrofit {
        val baseUrl = if (AdSdk.debug) TEST_BASE_URL else BASE_URL
        return Retrofit.Builder().client(createOkHttpClient())
            .baseUrl(baseUrl)
            .addConverterFactory(JsonFactory.json.asConverterFactory("application/json".toMediaType()))
            .build()
    }

}